<!-- Database Maintenance Tab -->
<div id="tabMaintenanceBatch" class="tab-content" role="tabpanel">
    <div class="endpoint-section">
        <h2>Batch Operations</h2>
        <p>Perform batch operations on database items</p>

        <div class="form-group">
            <label for="batchOperation">Operation Type:</label>
            <select id="batchOperation">
                <option value="delete_media">Delete Media Items</option>
                <option value="cleanup_orphans">Cleanup Orphaned Records</option>
                <option value="rebuild_fts">Rebuild Full-Text Search</option>
                <option value="vacuum_db">Vacuum Database</option>
                <option value="clear_cache">Clear Caches</option>
                <option value="export_data">Export Data</option>
                <option value="backup_db">Backup Database</option>
            </select>
        </div>

        <div id="batchFields">
            <!-- Dynamic fields based on operation -->
        </div>

        <div class="btn-group">
            <button class="btn btn-warning" id="btnBatchExecute">
                Execute Batch Operation
            </button>
            <button class="btn btn-secondary" id="btnBatchPreview">
                Preview
            </button>
        </div>

        <div id="batchProgress" style="display: none; margin-top: 20px;">
            <div class="progress-bar">
                <div id="batchProgressBar" class="progress-fill" style="width: 0%"></div>
            </div>
            <div id="batchProgressText">Processing...</div>
        </div>

        <pre id="batchResult"></pre>
    </div>
</div>

<div id="tabMaintenanceCleanup" class="tab-content" role="tabpanel">
    <div class="endpoint-section">
        <h2>Database Cleanup</h2>
        <p>Clean up and optimize database</p>

        <div class="form-group">
            <h3>Cleanup Options</h3>

            <label>
                <input type="checkbox" id="cleanup_temp_files" checked>
                Remove temporary files
            </label><br>

            <label>
                <input type="checkbox" id="cleanup_orphaned_embeddings" checked>
                Remove orphaned embeddings
            </label><br>

            <label>
                <input type="checkbox" id="cleanup_old_versions">
                Remove old media versions (keep latest 3)
            </label><br>

            <label>
                <input type="checkbox" id="cleanup_error_logs">
                Clear error logs older than 30 days
            </label><br>

            <label>
                <input type="checkbox" id="cleanup_expired_sessions">
                Remove expired sessions
            </label>
        </div>

        <div class="form-group">
            <label for="cleanup_dry_run">
                <input type="checkbox" id="cleanup_dry_run" checked>
                Dry Run (preview only, no changes)
            </label>
        </div>

        <button class="btn btn-warning" id="btnCleanupRun">
            Run Cleanup
        </button>

        <pre id="cleanupResult"></pre>
    </div>
</div>

<div id="tabMaintenanceExportImport" class="tab-content" role="tabpanel">
    <div class="endpoint-section">
        <h2>Export Configuration</h2>
        <p>Export system configuration and settings</p>

        <div class="form-group">
            <label>Export Options:</label>

            <label>
                <input type="checkbox" id="export_config" checked>
                Configuration Settings
            </label><br>

            <label>
                <input type="checkbox" id="export_prompts" checked>
                Prompt Library
            </label><br>

            <label>
                <input type="checkbox" id="export_characters">
                Character Cards
            </label><br>

            <label>
                <input type="checkbox" id="export_api_keys">
                API Keys (encrypted)
            </label><br>

            <label>
                <input type="checkbox" id="export_custom_settings">
                Custom Settings
            </label>
        </div>

        <div class="form-group">
            <label for="export_format">Export Format:</label>
            <select id="export_format">
                <option value="json">JSON</option>
                <option value="yaml">YAML</option>
                <option value="zip">ZIP Archive</option>
            </select>
        </div>

        <button class="btn btn-primary" id="btnExportConfig">
            Export Configuration
        </button>

        <pre id="exportResult"></pre>
    </div>

    <div class="endpoint-section">
        <h2>Import Configuration</h2>
        <p>Import system configuration from file</p>

        <div class="form-group">
            <label for="importFile">Configuration File:</label>
            <input type="file" id="importFile" accept=".json,.yaml,.yml,.zip">
        </div>

        <div class="form-group">
            <label>Import Options:</label>

            <label>
                <input type="checkbox" id="import_backup" checked>
                Create backup before import
            </label><br>

            <label>
                <input type="checkbox" id="import_merge">
                Merge with existing (don't overwrite)
            </label><br>

            <label>
                <input type="checkbox" id="import_validate" checked>
                Validate before import
            </label>
        </div>

        <button class="btn btn-warning" id="btnImportConfig">
            Import Configuration
        </button>

        <pre id="importResult"></pre>
    </div>
</div>

<div id="tabMaintenanceBackup" class="tab-content" role="tabpanel">
    <div class="endpoint-section">
        <h2>Database Backup & Restore</h2>

        <div class="form-group">
            <h3>Create Backup</h3>

            <label for="backup_name">Backup Name:</label>
            <input type="text" id="backup_name" placeholder="backup_2024_01_01">
            <small>Leave empty for auto-generated name</small>
        </div>

        <div class="form-group">
            <label>Backup Options:</label>

            <label>
                <input type="checkbox" id="backup_media_db" checked>
                Media Database
            </label><br>

            <label>
                <input type="checkbox" id="backup_vector_db" checked>
                Vector Database (ChromaDB)
            </label><br>

            <label>
                <input type="checkbox" id="backup_notes_db" checked>
                Notes Database
            </label><br>

            <label>
                <input type="checkbox" id="backup_compress" checked>
                Compress Backup
            </label>
        </div>

        <button class="btn btn-primary" id="btnCreateBackup">
            Create Backup
        </button>

        <pre id="backupResult"></pre>
    </div>

    <div class="endpoint-section">
        <h3>Restore from Backup</h3>

        <div class="form-group">
            <label for="restore_file">Backup File:</label>
            <input type="file" id="restore_file" accept=".db,.sql,.zip,.tar.gz">
        </div>

        <div class="form-group">
            <label for="restore_confirm">
                <input type="checkbox" id="restore_confirm">
                I understand this will overwrite existing data
            </label>
        </div>

        <button class="btn btn-danger" disabled id="restoreBtn">
            Restore Backup
        </button>

        <pre id="restoreResult"></pre>
    </div>
</div>

<!-- Claims Management Tab -->
<div id="tabClaims" class="tab-content" role="tabpanel">
    <div class="endpoint-section">
        <h2>Claims (Factual Statements)</h2>
        <div class="columns">
            <div class="column">
                <div class="form-group">
                    <label for="claims_media_id">Media ID</label>
                    <input id="claims_media_id" type="number" min="1" placeholder="Enter media_id" />
                </div>
                <div class="btn-group">
                    <button class="btn" id="btnClaimsLoad">Load Claims</button>
                    <button class="btn btn-warning" id="btnClaimsRebuildOne">Rebuild (Background)</button>
                </div>
            </div>
            <div class="column">
                <div class="form-group">
                    <label>Rebuild All Policy</label>
                    <select id="claims_rebuild_policy">
                        <option value="missing">Missing</option>
                        <option value="stale">Stale</option>
                        <option value="all">All</option>
                    </select>
                </div>
                <div class="btn-group">
                    <button class="btn btn-warning" id="btnClaimsRebuildAll">Rebuild All</button>
                    <button class="btn btn-secondary" id="btnClaimsRebuildFTS">Rebuild FTS Index</button>
                </div>
            </div>
        </div>
        <pre id="claims_output" style="min-height:160px; white-space: pre-wrap;"></pre>
    </div>
    <script>
        async function uiClaimsLoad() {
            const out = document.getElementById('claims_output');
            const mid = parseInt(document.getElementById('claims_media_id').value || '0', 10);
            if (!mid) { out.textContent = 'Enter a valid media_id'; return; }
            try {
                const resp = await fetch(`/api/v1/claims/${mid}`);
                if (!resp.ok) throw new Error(await resp.text());
                const data = await resp.json();
                out.textContent = JSON.stringify(data, null, 2);
            } catch (e) {
                out.textContent = 'Error: ' + e;
            }
        }
        async function uiClaimsRebuildOne() {
            const out = document.getElementById('claims_output');
            const mid = parseInt(document.getElementById('claims_media_id').value || '0', 10);
            if (!mid) { out.textContent = 'Enter a valid media_id'; return; }
            try {
                const resp = await fetch(`/api/v1/claims/${mid}/rebuild`, { method: 'POST' });
                if (!resp.ok) throw new Error(await resp.text());
                const data = await resp.json();
                out.textContent = 'Rebuild queued: ' + JSON.stringify(data);
            } catch (e) {
                out.textContent = 'Error: ' + e;
            }
        }
        async function uiClaimsRebuildAll() {
            const out = document.getElementById('claims_output');
            const pol = document.getElementById('claims_rebuild_policy').value;
            try {
                const resp = await fetch(`/api/v1/claims/rebuild/all?policy=${encodeURIComponent(pol)}`, { method: 'POST' });
                if (!resp.ok) throw new Error(await resp.text());
                const data = await resp.json();
                out.textContent = 'Rebuild all queued: ' + JSON.stringify(data);
            } catch (e) {
                out.textContent = 'Error: ' + e;
            }
        }
        async function uiClaimsRebuildFTS() {
            const out = document.getElementById('claims_output');
            try {
                const resp = await fetch(`/api/v1/claims/rebuild_fts`, { method: 'POST' });
                if (!resp.ok) throw new Error(await resp.text());
                const data = await resp.json();
                out.textContent = 'FTS index rebuilt: ' + JSON.stringify(data);
            } catch (e) {
                out.textContent = 'Error: ' + e;
            }
        }
    </script>
</div>
<style>
.progress-bar {
    width: 100%;
    height: 30px;
    background: #f0f0f0;
    border-radius: 15px;
    overflow: hidden;
    margin: 10px 0;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #4CAF50, #45a049);
    transition: width 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
}

.maintenance-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin: 20px 0;
}

.stat-card {
    padding: 15px;
    background: var(--color-surface-alt);
    border-radius: 8px;
    text-align: center;
}

.stat-value {
    font-size: 2rem;
    font-weight: bold;
    color: var(--color-primary);
}

.stat-label {
    color: var(--color-text-muted);
    margin-top: 5px;
}
</style>

<script type="module" src="js/maintenance.js"></script>

<!-- Legacy inline script removed; migrated to js/maintenance.js -->
<!--
function updateBatchFields() {
    const operation = document.getElementById('batchOperation').value;
    const fieldsDiv = document.getElementById('batchFields');

    let html = '';

    switch(operation) {
        case 'delete_media':
            html = `
                <div class="form-group">
                    <label for="batch_media_ids">Media IDs (comma-separated or range):</label>
                    <textarea id="batch_media_ids" rows="4" placeholder="1,2,3 or 1-100 or combination"></textarea>
                    <small>Examples: "1,2,3" or "1-10" or "1-5,10,15-20"</small>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="batch_permanent_delete">
                        Permanent delete (bypass trash)
                    </label>
                </div>
            `;
            break;

        case 'cleanup_orphans':
            html = `
                <div class="form-group">
                    <p>This will find and remove:</p>
                    <ul>
                        <li>Embeddings without media items</li>
                        <li>Transcripts without media items</li>
                        <li>Versions without parent media</li>
                    </ul>
                </div>
            `;
            break;

        case 'export_data':
            html = `
                <div class="form-group">
                    <label for="batch_export_type">Export Type:</label>
                    <select id="batch_export_type">
                        <option value="all">All Data</option>
                        <option value="media">Media Items</option>
                        <option value="prompts">Prompts</option>
                        <option value="notes">Notes</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="batch_export_format">Format:</label>
                    <select id="batch_export_format">
                        <option value="json">JSON</option>
                        <option value="csv">CSV</option>
                        <option value="sql">SQL</option>
                    </select>
                </div>
            `;
            break;
    }

    fieldsDiv.innerHTML = html;
}

async function performBatchOperation() {
    const operation = document.getElementById('batchOperation').value;
    const resultEl = document.getElementById('batchResult');
    const progressDiv = document.getElementById('batchProgress');
    const progressBar = document.getElementById('batchProgressBar');
    const progressText = document.getElementById('batchProgressText');

    // Show progress
    progressDiv.style.display = 'block';
    resultEl.textContent = '';

    try {
        // Build request based on operation type
        let endpoint = '/api/v1/maintenance/batch';
        let payload = { operation };

        switch(operation) {
            case 'delete_media':
                const idsText = document.getElementById('batch_media_ids').value;
                payload.media_ids = parseMediaIds(idsText);
                payload.permanent = document.getElementById('batch_permanent_delete').checked;
                break;

            case 'export_data':
                payload.export_type = document.getElementById('batch_export_type').value;
                payload.format = document.getElementById('batch_export_format').value;
                endpoint = '/api/v1/maintenance/export';
                break;
        }

        // Simulate progress (replace with actual progress tracking)
        let progress = 0;
        const progressInterval = setInterval(() => {
            progress = Math.min(progress + 10, 90);
            progressBar.style.width = progress + '%';
            progressText.textContent = `Processing... ${progress}%`;
        }, 200);

        // Make request
        const response = await apiClient.post(endpoint, payload);

        // Complete progress
        clearInterval(progressInterval);
        progressBar.style.width = '100%';
        progressText.textContent = 'Complete!';

        // Display result
        resultEl.textContent = JSON.stringify(response, null, 2);

        setTimeout(() => {
            progressDiv.style.display = 'none';
        }, 2000);

    } catch (error) {
        progressDiv.style.display = 'none';
        resultEl.textContent = `Error: ${error.message}`;
        Toast.error(`Batch operation failed: ${error.message}`);
    }
}

// Parse media IDs from text (supports ranges)
function parseMediaIds(text) {
    const ids = [];
    const parts = text.split(',');

    parts.forEach(part => {
        part = part.trim();
        if (part.includes('-')) {
            // Range
            const [start, end] = part.split('-').map(n => parseInt(n.trim()));
            for (let i = start; i <= end; i++) {
                ids.push(i);
            }
        } else if (part) {
            // Single ID
            ids.push(parseInt(part));
        }
    });

    return ids;
}

// Database cleanup
async function performDatabaseCleanup() {
    const resultEl = document.getElementById('cleanupResult');
    const dryRun = document.getElementById('cleanup_dry_run').checked;

    const options = {
        temp_files: document.getElementById('cleanup_temp_files').checked,
        orphaned_embeddings: document.getElementById('cleanup_orphaned_embeddings').checked,
        old_versions: document.getElementById('cleanup_old_versions').checked,
        error_logs: document.getElementById('cleanup_error_logs').checked,
        expired_sessions: document.getElementById('cleanup_expired_sessions').checked,
        dry_run: dryRun
    };

    try {
        Loading.show(resultEl.parentElement, dryRun ? 'Analyzing...' : 'Cleaning...');

        const response = await apiClient.post('/api/v1/maintenance/cleanup', options);

        resultEl.textContent = JSON.stringify(response, null, 2);
        Toast.success(dryRun ? 'Analysis complete' : 'Cleanup complete');

    } catch (error) {
        resultEl.textContent = `Error: ${error.message}`;
        Toast.error(`Cleanup failed: ${error.message}`);
    } finally {
        Loading.hide(resultEl.parentElement);
    }
}

// Export configuration
async function exportConfiguration() {
    const resultEl = document.getElementById('exportResult');

    const options = {
        config: document.getElementById('export_config').checked,
        prompts: document.getElementById('export_prompts').checked,
        characters: document.getElementById('export_characters').checked,
        api_keys: document.getElementById('export_api_keys').checked,
        custom_settings: document.getElementById('export_custom_settings').checked,
        format: document.getElementById('export_format').value
    };

    try {
        const response = await apiClient.post('/api/v1/maintenance/export-config', options);

        // If it's a file, trigger download
        if (options.format === 'zip') {
            const blob = new Blob([response], { type: 'application/zip' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `tldw_config_${Date.now()}.zip`;
            a.click();
            URL.revokeObjectURL(url);
            resultEl.textContent = 'Configuration exported successfully';
        } else {
            resultEl.textContent = JSON.stringify(response, null, 2);
        }

        Toast.success('Configuration exported');

    } catch (error) {
        resultEl.textContent = `Error: ${error.message}`;
        Toast.error(`Export failed: ${error.message}`);
    }
}

async function importConfiguration() {
    const resultEl = document.getElementById('importResult');
    const fileInput = document.getElementById('importFile');

    if (!fileInput.files.length) {
        Toast.error('Please select a file to import');
        return;
    }

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    formData.append('backup', document.getElementById('import_backup').checked);
    formData.append('merge', document.getElementById('import_merge').checked);
    formData.append('validate', document.getElementById('import_validate').checked);

    try {
        Loading.show(resultEl.parentElement, 'Importing configuration...');

        const response = await apiClient.post('/api/v1/maintenance/import-config', formData);

        resultEl.textContent = JSON.stringify(response, null, 2);
        Toast.success('Configuration imported successfully');

    } catch (error) {
        resultEl.textContent = `Error: ${error.message}`;
        Toast.error(`Import failed: ${error.message}`);
    } finally {
        Loading.hide(resultEl.parentElement);
    }
}

async function createBackup() {
    const resultEl = document.getElementById('backupResult');

    const options = {
        name: document.getElementById('backup_name').value || undefined,
        media_db: document.getElementById('backup_media_db').checked,
        vector_db: document.getElementById('backup_vector_db').checked,
        notes_db: document.getElementById('backup_notes_db').checked,
        compress: document.getElementById('backup_compress').checked
    };

    try {
        Loading.show(resultEl.parentElement, 'Creating backup...');

        const response = await apiClient.post('/api/v1/maintenance/backup', options, { timeout: 300000 }); // 5 min timeout

        resultEl.textContent = JSON.stringify(response, null, 2);
        Toast.success('Backup created successfully');

    } catch (error) {
        resultEl.textContent = `Error: ${error.message}`;
        Toast.error(`Backup failed: ${error.message}`);
    } finally {
        Loading.hide(resultEl.parentElement);
    }
}

async function restoreBackup() {
    const resultEl = document.getElementById('restoreResult');
    const fileInput = document.getElementById('restore_file');

    if (!fileInput.files.length) {
        Toast.error('Please select a backup file');
        return;
    }

    if (!confirm('This will overwrite your existing data. Are you absolutely sure?')) {
        return;
    }

    const formData = new FormData();
    formData.append('backup_file', fileInput.files[0]);

    try {
        Loading.show(resultEl.parentElement, 'Restoring backup...');

        const response = await apiClient.post('/api/v1/maintenance/restore', formData, { timeout: 600000 }); // 10 min timeout

        resultEl.textContent = JSON.stringify(response, null, 2);
        Toast.success('Backup restored successfully');

    } catch (error) {
        resultEl.textContent = `Error: ${error.message}`;
        Toast.error(`Restore failed: ${error.message}`);
    } finally {
        Loading.hide(resultEl.parentElement);
    }
}
-->
